package com.cocos.game;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustConfig;
import com.adjust.sdk.LogLevel;

import com.applovin.sdk.AppLovinMediationProvider;
import com.applovin.sdk.AppLovinPrivacySettings;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkInitializationConfiguration;
import com.applovin.sdk.AppLovinSdkSettings;
import com.cocos.game.zdkj.log.EventType;
import com.cocos.game.zdkj.log.LogReporter;
import com.cocos.game.zdkj.model.DeviceLogRecord;
import com.cocos.service.SDKWrapper;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.sheepy.game.BuildConfig;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;

public class MApplication extends Application {
    public static MApplication instance;

    private static final String TAG = "MApplication";

    public static final String REWARDED_AD_UNIT_ID = "eb84543c4549ef62";
    public static final String INTERSTITIAL_AD_UNIT_ID = "fc8097d9d4a4b15a";
    public static final String APPLOVIN_APP_KEY = "9Lpwk0QhylrZ0Q6kEw8i_CTkJ6T0OTT6yrGrCmTfhFWT8zaMrofbCyBeTk1OVGqNDXvPaLMHhv_DHB3B7KAnV7";
    public static final String AD_JUST_KEY = "f3ir1o5moykg";

    public static final String AUDIT_END_TIME = "2024-09-01 14:00:00";


    public static final Map<String, ConcurrentLinkedQueue<JSONObject>> requestMap = new HashMap<>();

    public static ConcurrentLinkedQueue<JSONObject> getRequestQueue(String queueName) {
        if (!requestMap.containsKey(queueName)) {
            requestMap.put(queueName, new ConcurrentLinkedQueue<>());
        }
        return requestMap.get(queueName);
    }

    public boolean isApplovinInitOk = false;
    public boolean isFirstLoadAdStart = false;


    private boolean isInitAdjust = false;

    public static final boolean isReturnTest = false;

    // todo 是否一直返回B面
    public static boolean isReturnB = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        // 冷启动埋点
        LogReporter.logReport(EventType.cold_start, null);
        initAdid();

        initAdjustV2();
        initApplovin();

        initFirebase();
    }


    private void initFirebase() {
        FirebaseAnalytics.getInstance(this).setUserId(DeviceUtil.getDeviceId());
        if (!MAppCacheManager.getADID().isEmpty()) {
            FirebaseAnalytics.getInstance(this).setUserProperty("adid", MAppCacheManager.getADID());
        }
    }

    private void initAdid() {
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
                    Log.e(TAG, "ADID from Self: " + advertisingIdInfo.getId());
                    if (advertisingIdInfo.getId() != null && !advertisingIdInfo.getId().isEmpty()) {
                        MAppCacheManager.setADID(advertisingIdInfo.getId());
                        LogReporter.logReport(EventType.adid, null);
//                        AppLovinSdk.getInstance(MApplication.instance).getSettings().setExtraParameter("adid", MAppCacheManager.getADID());
                        Adjust.addGlobalCallbackParameter("adid", advertisingIdInfo.getId());
                        FirebaseAnalytics.getInstance(MApplication.instance).setUserProperty("adid", MAppCacheManager.getADID());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void initApplovin() {
        // Create the initialization configuration
        AppLovinSdkInitializationConfiguration initConfig = AppLovinSdkInitializationConfiguration
                .builder(APPLOVIN_APP_KEY, this)
                .setMediationProvider(AppLovinMediationProvider.MAX)
                .build();

        AppLovinPrivacySettings.setHasUserConsent(true, this);
//        AppLovinPrivacySettings.setIsAgeRestrictedUser(false, this);
        AppLovinPrivacySettings.setDoNotSell(false, this);
        AppLovinSdkSettings settings = AppLovinSdk.getInstance(this).getSettings();
        settings.setVerboseLogging(BuildConfig.DEBUG);
        settings.setUserIdentifier(DeviceUtil.getDeviceId());
        Log.e(TAG, "ADID applovin init adid:" + MAppCacheManager.getADID());
//        if (!MAppCacheManager.getADID().isEmpty()){
//            settings.setExtraParameter("adid", MAppCacheManager.getADID());
//        }
//        AppLovinSdk.getInstance( this ).getSettings().setVerboseLogging(BuildConfig.DEBUG);

        // Initialize the SDK with the configuration
        AppLovinSdk.getInstance(this).initialize(initConfig, sdkConfig -> {
            // Start loading ads
            Log.d(TAG, "onSdkInitialized: " + sdkConfig.toString());
            isApplovinInitOk = true;
            if (!MAppCacheManager.getDeviceLogRecord().isUserInitMax()) {
                LogReporter.logReport(EventType.user_init_max, null);
                DeviceLogRecord deviceLogRecord = MAppCacheManager.getDeviceLogRecord();
                deviceLogRecord.setUserInitMax(true);
                MAppCacheManager.setDeviceLogRecord(deviceLogRecord);
                MAppCacheManager.setUserMaxInitTime(ZDKJUtils.getCurrentUTCDate());
            }
            LogReporter.logReport(EventType.init_max_success, null);

            if (!isFirstLoadAdStart) {
                try {
                    if (SDKWrapper.shared() != null
                            && SDKWrapper.shared().getActivity() != null
                            && SDKWrapper.shared().getActivity() instanceof BaseAdActivity) {
                        ((BaseAdActivity) SDKWrapper.shared().getActivity()).firstLoadAd();
                    }
                }catch (Throwable throwable){
                    Log.d(TAG, "initApplovin: ",throwable);
                }

            }
//            initAdjust();
        });
        if (BuildConfig.DEBUG) {
            AppLovinSdk.getInstance(this).getSettings().setVerboseLogging(true);
        }
    }

    /**
     * 初始化Adjust
     */
    public void initAdjust() {
        // TODO: 2024/7/8 Adjust environment
//        Log.d(TAG, "Adjust.isEnabled: " + Adjust.isEnabled() + " isAdjustInit: " + isInitAdjust + " idfa: " + Adjust.getAdid());
//        if (!isInitAdjust) {
//            String environment = AdjustConfig.ENVIRONMENT_SANDBOX;
//            AdjustConfig adjustConfig = new AdjustConfig(getApplicationContext(), AD_JUST_KEY, environment);
//            Adjust.onCreate(adjustConfig);
//            registerActivityLifecycleCallbacks(new AdjustLifecycleCallbacks());
//            isInitAdjust = true;
//        }
    }

    /**
     * 初始化Adjust
     */
    public void initAdjustV2() {
        String environment = BuildConfig.DEBUG ? AdjustConfig.ENVIRONMENT_SANDBOX : AdjustConfig.ENVIRONMENT_PRODUCTION;
        AdjustConfig adjustConfig = new AdjustConfig(getApplicationContext(), AD_JUST_KEY, environment);
        adjustConfig.setExternalDeviceId(DeviceUtil.getDeviceId());
        adjustConfig.setLogLevel(BuildConfig.DEBUG ? LogLevel.VERBOSE : LogLevel.INFO);
        adjustConfig.setOnAttributionChangedListener(attribution -> {
            Log.d(TAG, "Adjust onChange attr: " + attribution);
        });
        // Adjust 添加参数
        Adjust.addGlobalCallbackParameter("machineEquipmentId", DeviceUtil.getDeviceId());
        Adjust.addGlobalCallbackParameter("version", BuildConfig.VERSION_CODE + "");
        if (!MAppCacheManager.getADID().isEmpty()) {
            Adjust.addGlobalCallbackParameter("adid", MAppCacheManager.getADID());
        }
        Log.e(TAG, "ADID from Adjust: " + MAppCacheManager.getADID());
        Adjust.initSdk(adjustConfig);
        Adjust.getAttribution(adjustAttribution -> {
            Log.d(TAG, "Adjust init attr: " + adjustAttribution);
            if (!MAppCacheManager.getDeviceLogRecord().isUserInitAdjust()) {
                LogReporter.logReport(EventType.user_init_adjust, null);
                DeviceLogRecord deviceLogRecord = MAppCacheManager.getDeviceLogRecord();
                deviceLogRecord.setUserInitAdjust(true);
                MAppCacheManager.setDeviceLogRecord(deviceLogRecord);
            }

            Log.d(TAG, "Adjust init attr: " + adjustAttribution);
            if (!MAppCacheManager.getDeviceLogRecord().isUserInitAdjustSuccess()) {
                LogReporter.logReport(EventType.user_init_adjust_success, null);
                DeviceLogRecord deviceLogRecord = MAppCacheManager.getDeviceLogRecord();
                deviceLogRecord.setUserInitAdjustSuccess(true);
                MAppCacheManager.setDeviceLogRecord(deviceLogRecord);
            }
        });


        registerActivityLifecycleCallbacks(new AdjustLifecycleCallbacks());

    }

    private static final class AdjustLifecycleCallbacks
            implements ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull final Activity activity, @Nullable final Bundle bundle) {
        }

        @Override
        public void onActivityStarted(@NonNull final Activity activity) {
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            Adjust.onResume();
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            Adjust.onPause();
        }

        @Override
        public void onActivityStopped(@NonNull final Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull final Activity activity, @NonNull final Bundle bundle) {
        }

        @Override
        public void onActivityDestroyed(@NonNull final Activity activity) {
        }
    }

    public static String APPLICATION_ID() {
        return BuildConfig.APPLICATION_ID;
    }

    public static String VERSION_NAME() {
        return BuildConfig.VERSION_NAME;
    }

    public static Integer VERSION_CODE() {
        return BuildConfig.VERSION_CODE;
    }

    public static boolean DEBUG() {
        return BuildConfig.DEBUG;
    }

    public static String BUILD_TYPE() {
        return BuildConfig.BUILD_TYPE;
    }
}
